package com.yang.sso.oauth2.controller;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.yang.common.core.model.UserInfo;
import org.yang.common.core.result.BaseController;
import org.yang.common.core.result.R;
import org.yang.common.utils.jwt.JwtTokenAnalysisUtli;

import java.security.Principal;


/**
 * 授权/登录
 * @author: Islands
 * @create: 2024-04-12 21:59
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class AuthController extends BaseController {

    private final OAuth2AuthorizationService oAuth2AuthorizationService;

    /**
     * 获取登录用户信息
     * @return 登录用户信息
     */
    @GetMapping("userinfo")
    public R<UserInfo> userinfo(){
        UserInfo userInfo = JwtTokenAnalysisUtli.useMe();
        return R.success(userInfo);
    }

    @GetMapping("/check_token")
    public Authentication checkToken() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 退出登录
     * @param principal
     */
    @DeleteMapping("/logout")
    public void logout(Principal principal) {
        if (principal instanceof JwtAuthenticationToken token) {
            final String tokenValue = token.getToken().getTokenValue();
            oAuth2AuthorizationService.remove(oAuth2AuthorizationService.findByToken(tokenValue, OAuth2TokenType.ACCESS_TOKEN));
        }
    }
}
